package com.youxue.controller;

import com.alibaba.fastjson.JSONObject;
import com.cangshi.permission.entity.CorrectJSONObject;
import com.cangshi.permission.entity.UserSubject;
import com.youxue.entity.*;
import com.youxue.permission.saver.SubjectHolder;
import com.youxue.service.DynamicService;
import com.youxue.service.InteractionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by 15c on 2018/1/20.
 */
@Controller
@RequestMapping("/interaction")
public class InteractionController {
    @Autowired
    InteractionService interactionService;


    /**
     * （no）
     * 查看一个动态的某个人的评论
     * 查询结果：（user表示评论者对象；user1表示被评论的用户对象《replay_id所对应的对象》）
     *
     * @param dynamicId 动态id
     * @param replayId  被评论者id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/info/onePerson", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String getOneInfo(@RequestParam(required = false) Integer dynamicId, @RequestParam(required = false) Integer replayId) {
        if (null == dynamicId || null == replayId) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(101, "参数不完整");
            return JSONObject.toJSONString(errorJsonObject);
        }

        List<Interaction> interactionList = interactionService.showOnePersonReview(dynamicId, replayId);
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("该人的所有评论信息获取成功");
        correctJsonObject.setData(interactionList);
        return correctJsonObject.toString();
    }


    /**
     * 添加一条动态直接评论
     *
     * @param interaction （不含ReplayId<回复者id>、parentId、interactionUserId<评价者id>）
     * @return
     */

    @ResponseBody
    @RequestMapping(value = "/add/comment", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String insertReview(@RequestBody(required = false) Interaction interaction) {
        if (null == interaction.getDynamicId() || null == interaction.getDynamicComment()) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(102, "参数不完整");
            return JSONObject.toJSONString(errorJsonObject);
        }
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        //评论者用户id
        interaction.setInteractionUserId(userId);
        //parentId,replayId设为0表示该评论为直接评论
        interaction.setReplayId(0);
        interaction.setParentId(0);
        //添加动态直接评论
        int result = interactionService.addADynamicInteraction(interaction);
        if (1 != result) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(103, "发布失败，请重试");
            return JSONObject.toJSONString(errorJsonObject);
        }
        return new CorrectJSONObject("评论成功").toString();
    }

    /**
     * 添加一条动态评论下面的回复
     *
     * @param interaction （不含interactionUserId<评价者id>，parentId为当前回复的这条评论所对应的interactionId，replayId为当前回复的这条评论所对应的评论者Id）
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/add/Reply", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String insertReply(@RequestBody(required = false) Interaction interaction) {
        if (null == interaction.getDynamicId() || null == interaction.getDynamicComment() || null == interaction.getReplayId() || null == interaction.getParentId()) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(104, "参数不完整");
            return JSONObject.toJSONString(errorJsonObject);
        }
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        //评论者用户id
        interaction.setInteractionUserId(userId);
        //添加评论回复
        int result = interactionService.addADynamicInteraction(interaction);
        if (1 != result) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(105, "评论回复失败，请重试");
            return JSONObject.toJSONString(errorJsonObject);
        }
        return new CorrectJSONObject("评论回复成功").toString();
    }

    /**
     * 删除一条动态直接评论
     *
     * @param interactionId
     * @param interactionUserId 该评论的评论者id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete/comment", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String deleteAComment(@RequestParam(required = false) Integer interactionId,
                          @RequestParam(required = false) Integer interactionUserId) {
        if (null == interactionId || null == interactionUserId) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(106, "参数不完整");
            return JSONObject.toJSONString(errorJsonObject);
        }
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        if (userId != interactionUserId) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(107, "请删除自己的评论");
            return JSONObject.toJSONString(errorJsonObject);
        }
        int result = interactionService.deleteADynamicInteraction(interactionId);
        if (1 != result) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(108, "评论删除失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
        return new CorrectJSONObject("评论删除成功").toString();

    }

    /**
     * 删除一条评论下方回复
     *
     * @param interactionId
     * @param interactionUserId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete/interaction", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String deleteAInteraction(@RequestParam(required = false) Integer interactionId,
                              @RequestParam(required = false) Integer interactionUserId) {
        if (null == interactionId || null == interactionUserId) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(109, "参数不完整");
            return JSONObject.toJSONString(errorJsonObject);
        }
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        if (userId != interactionUserId) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(110, "请删除自己的回复");
            return JSONObject.toJSONString(errorJsonObject);
        }
        int result = interactionService.deleteAInteraction(interactionId);
        if (1 != result) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(111, "回复删除失败");
            return JSONObject.toJSONString(errorJsonObject);
        }
        return new CorrectJSONObject("回复删除成功").toString();
    }

    @Autowired
    DynamicService dynamicService;

    /**
     * 分页查询一条动态下所有的直接评论(返回的allInteractionCount表示一条评论下的所有回复总条数；user1表示评论者对象；user表示动态发布者对象,dynamic表示该动态信息)
     *
     * @param dynamicId 需要查看的动态id
     * @param page      请求页数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/show/comments", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showADynamicAllCommentByPage(@RequestParam(required = false) Integer dynamicId,
                                        @RequestParam(required = false) Integer page) {
        if (null == dynamicId || null == page) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(112, "参数不完整");
            return JSONObject.toJSONString(errorJsonObject);
        }
        //一页的信息条数
        int pageSize = 15;
        //获得总页数
        int allTaskNum = interactionService.showADynamicAllCommentCount(dynamicId);
        int resultAllPage = allTaskNum / pageSize;
        int resultRemainder = allTaskNum % pageSize;
        if (0 < resultRemainder) {
            resultAllPage = resultAllPage + 1;
        }
        if (0 >= page) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(113, "page参数不可为负");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (resultAllPage < page) {
            //请求页数超额,表示该动态暂未有评论，此时只查出动态、与动态发布用户详情
            //返回数据中user依然代表动态发布者对象，dynamic表示该动态对象
            Dynamic dynamic = new Dynamic();
            dynamic = dynamicService.showOneDynamic(dynamicId);
            if(null==dynamic){
                ErrorJsonObject errorJsonObject = new ErrorJsonObject(114, "dynamicId有误，无法查到对应动态详情");
                return JSONObject.toJSONString(errorJsonObject);
            }
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("该动态暂未有任何评论，动态、动态发布者详情查询成功");
            correctJsonObject.setData(dynamic);
            correctJsonObject.put("allPage",resultAllPage);
            //存入一条动态所有直接评论总条数
            correctJsonObject.put("allCommentCount",interactionService.showADynamicAllCommentCount(dynamicId));
            //ErrorJsonObject errorJsonObject = new ErrorJsonObject(114, "请求页数超额");
            return JSONObject.toJSONString(correctJsonObject);
        }
        int startPos = pageSize * page - pageSize;
        int allCount = 0;
        List<Interaction> interactionArrayList = new ArrayList<Interaction>();
        interactionArrayList = interactionService.showADynamicAllCommentByPage(dynamicId, startPos, pageSize);
        //遍历集合，存入一条评论下有多少条回复
        for (Interaction interaction : interactionArrayList) {
            //查询对应评论下的回复总条数
            allCount = interactionService.aCommentAllInteractionCount(interaction.getInteractionId());
            //在对象中存入总条数
            interaction.setAllInteractionCount(allCount);
        }
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
        correctJsonObject.setData(interactionArrayList);
        correctJsonObject.put("allPage",resultAllPage);
        //存入一条动态所有直接评论总条数
        correctJsonObject.put("allCommentCount",interactionService.showADynamicAllCommentCount(dynamicId));
        return JSONObject.toJSONString(correctJsonObject);
    }

    /**
     * 分页查询一条评论下所有的回复(user表示本条评论的评论者对象；user1表示回复者对象《interactionUserId》，user2表示被回复者对象《replayId》，interaction1表示回复内容对象，interaction2表示评论内容对象)
     * ps：其中数据较多，请按给出的对象指向放值
     *
     * @param interactionId 需要查看的评论id
     * @param page          请求页数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/show/interactions", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showACommentAllInteractionByPage(@RequestParam(required = false) Integer interactionId,
                                            @RequestParam(required = false) Integer page) {
        if (null == interactionId || null == page) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(115, "参数不完整");
            return JSONObject.toJSONString(errorJsonObject);
        }
        //一页的信息条数
        int pageSize = 15;
        //获得总页数
        int allTaskNum = interactionService.aCommentAllInteractionCount(interactionId);
        int resultAllPage = allTaskNum / pageSize;
        int resultRemainder = allTaskNum % pageSize;
        if (0 < resultRemainder) {
            resultAllPage = resultAllPage + 1;
        }
        if (0 >= page) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(116, "page参数不可为负");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (resultAllPage < page) {
            //请求页数超额,表示该评论暂未有回复，此时只查出评论、与评论用户详情
            //返回数据中user依然代表评论用户对象，interaction2表示评论内容对象
            Interaction interaction2=new Interaction();
            interaction2=interactionService.showAInteractionInfo(interactionId);
            if(null==interaction2){
                ErrorJsonObject errorJsonObject = new ErrorJsonObject(117, "interactionId有误，无法查到对应评论详情");
                return JSONObject.toJSONString(errorJsonObject);
            }
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("该评论暂未有任何回复，评论、评论者详情查询成功");
            correctJsonObject.setData(interaction2);
            correctJsonObject.put("allPage",resultAllPage);
            //ErrorJsonObject errorJsonObject = new ErrorJsonObject(114, "请求页数超额");
            return JSONObject.toJSONString(correctJsonObject);
        }
        int startPos = pageSize * page - pageSize;
        List<Interaction> interactionArrayList = new ArrayList<Interaction>();
        interactionArrayList = interactionService.showACommentAllInteractionByPage(interactionId, startPos, pageSize);

        CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
        correctJsonObject.setData(interactionArrayList);
        correctJsonObject.put("allPage",resultAllPage);
        return JSONObject.toJSONString(correctJsonObject);
    }

    /***
     * 查看我的未读消息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/show/mynews", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showNews() {
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();

        List<Interaction> interactionList = interactionService.whatchMyNews(userId);
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("信息获取成功");
        correctJsonObject.setData(interactionList);

        return correctJsonObject.toString();
    }

    /**
     * 查询未读消息总条数
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/show/mynews/count", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showNewsCount() {
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
        correctJsonObject.setData(interactionService.whatchMyNewsCount(userId));
        return JSONObject.toJSONString(correctJsonObject);
    }

    /**
     * 设置一条消息为已读
     *
     * @param interactionId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/read/amynews", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String readANews(@RequestParam(required = false) Integer interactionId) {
        if (null == interactionId) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(119, "参数不完整");
            return JSONObject.toJSONString(errorJsonObject);
        }
        int result = interactionService.readAInteraction(interactionId);
        if (1 != result) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(120, "忽略消息出错");

            return JSONObject.toJSONString(errorJsonObject);
        }
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("忽略消息成功");
        return JSONObject.toJSONString(correctJsonObject);
    }

    /**
     * 设置某个用户全部未读消息为已读
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/read/listmynews", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String readListNews() {
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();

        int result = interactionService.readListInteraction(userId);
        if (0 == result) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(121, "忽略全部消息出错");

            return JSONObject.toJSONString(errorJsonObject);
        }
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("忽略全部消息成功");
        return JSONObject.toJSONString(correctJsonObject);
    }

    /**
     * 动态评价回复图片上传入口
     *
     * @param request 用户请求
     * @param image   图片
     * @return 结果json
     */
    @ResponseBody
    @RequestMapping(value = "/image-upload", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String imageUpload(HttpServletRequest request, @RequestBody(required = false) String image) {
        System.out.println("image为：" + image + " end");
        ErrorJsonObject errorJsonObject;
        //指定头类型
        String headerPng = "data:image/png;base64,";
        String headerJpG = "data:image/jpeg;base64,";

        //获取服务器的路径
        String realPath = request.getSession().getServletContext().getRealPath("/resources/interactionImg");

        System.out.println("realPath为：" + realPath + "  end");
        //声明图片地址
        String imgAddress = null;
        //获取扩展名
        String extensionName = ".png";
        System.out.println("--------------->" + extensionName);
        if (image != null && (image.indexOf(headerPng) != 0 || image.indexOf(headerJpG) != 0)) {
            String headPng = image.substring(0, headerPng.length());
            String headJpG = image.substring(0, headerJpG.length());
            if (headerJpG.equals(headJpG)) {
                //去掉头部
                image = image.substring(headerJpG.length());
                BASE64Decoder decoder = new BASE64Decoder();
                try {
                    if (!image.isEmpty()) {

                        //以当前时间加随机数命名上传文件
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                        String date = sdf.format(new java.util.Date());


                        //设置图片名为当前时间加随机数
                        imgAddress = date + new Random().nextInt() + extensionName;

                        //将文件上传到服务器
                        byte[] decodedBytes = decoder.decodeBuffer(image);

                        FileOutputStream out = new FileOutputStream(realPath + "/" + imgAddress);

                        out.write(decodedBytes);

                        out.close();

                        CorrectJsonObject correctJsonObject = new CorrectJsonObject("上传成功！");
                        correctJsonObject.setData(imgAddress);
                        return correctJsonObject.toString();

                    } else {

                        errorJsonObject = new ErrorJsonObject(108, "上传的文件不存在！");
                        return errorJsonObject.toJSONString();

                    }
                } catch (IOException e) {

                    errorJsonObject = new ErrorJsonObject(108, e.getMessage());
                    return errorJsonObject.toJSONString();

                }
            } else if (headerPng.equals(headPng)) {
                //去掉头部
                image = image.substring(headerPng.length());
                BASE64Decoder decoder = new BASE64Decoder();
                try {
                    if (!image.isEmpty()) {

                        //以当前时间加随机数命名上传文件
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                        String date = sdf.format(new java.util.Date());


                        //设置图片名为当前时间加随机数
                        imgAddress = date + new Random().nextInt() + extensionName;

                        //将文件上传到服务器
                        byte[] decodedBytes = decoder.decodeBuffer(image);

                        FileOutputStream out = new FileOutputStream(realPath + "/" + imgAddress);

                        out.write(decodedBytes);

                        out.close();

                        CorrectJsonObject correctJsonObject = new CorrectJsonObject("上传成功！");
                        correctJsonObject.setData(imgAddress);
                        return correctJsonObject.toString();

                    } else {

                        errorJsonObject = new ErrorJsonObject(108, "上传的文件不存在！");
                        return errorJsonObject.toJSONString();

                    }
                } catch (IOException e) {

                    errorJsonObject = new ErrorJsonObject(108, e.getMessage());
                    return errorJsonObject.toJSONString();

                }
            } else {
                errorJsonObject = new ErrorJsonObject(107, "文件不存在或格式不正确");
                return errorJsonObject.toJSONString();
            }
        } else {
            errorJsonObject = new ErrorJsonObject(107, "文件不存在或格式不正确");
            return errorJsonObject.toJSONString();
        }
    }

}